<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { InfoFilled, Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import type { Question } from '@/utils/QuestionAnalysisSystem'
import { generateHeatmapData } from '@/utils/QuestionAnalysisSystem'

// 图表实例引用
const facilityTypeChartRef = ref<HTMLElement | null>(null)
const issuesChartRef = ref<HTMLElement | null>(null)
const timeDistributionChartRef = ref<HTMLElement | null>(null)
const questionHeatmapChartRef = ref<HTMLElement | null>(null)

// 图表实例
let facilityTypeChart: echarts.ECharts | null = null
let issuesChart: echarts.ECharts | null = null
let timeDistributionChart: echarts.ECharts | null = null
let geographicDistributionChart: echarts.ECharts | null = null
let questionHeatmapChart: echarts.ECharts | null = null

// 地图和图层引用
let view: MapView | null = null
let facilityLayer: FeatureLayer | null = null

// 统计数据
const statisticsData = reactive({
  facilityTypeData: [] as { name: string; value: number }[],
  issuesData: [] as { name: string; value: number }[],
  timeDistributionData: [] as { date: string; count: number }[],
  geographicData: [] as [number, number, number][],
  questionHeatmapData: [] as number[][],
  allQuestions: [] as Question[],
  totalFacilities: 0,
  totalIssues: 0,
  loading: false,
})

// 初始化
onMounted(() => {
  initCharts()
  loadStatisticsData()
})

onUnmounted(() => {
  // 销毁图表实例
  if (facilityTypeChart) {
    facilityTypeChart.dispose()
    facilityTypeChart = null
  }
  if (issuesChart) {
    issuesChart.dispose()
    issuesChart = null
  }
  if (timeDistributionChart) {
    timeDistributionChart.dispose()
    timeDistributionChart = null
  }
  if (geographicDistributionChart) {
    geographicDistributionChart.dispose()
    geographicDistributionChart = null
  }
  if (questionHeatmapChart) {
    questionHeatmapChart.dispose()
    questionHeatmapChart = null
  }
  // 销毁地图实例
  if (view) {
    view = null
  }
})

// 初始化图表
const initCharts = () => {
  // 初始化设施类型分布图表
  if (facilityTypeChartRef.value) {
    facilityTypeChart = echarts.init(facilityTypeChartRef.value)
    const option = {
      title: {
        text: '设施类型分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: [],
      },
      series: [
        {
          name: '设施类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [],
        },
      ],
    }
    facilityTypeChart.setOption(option)
  }

  // 初始化设施问题统计图表
  if (issuesChartRef.value) {
    issuesChart = echarts.init(issuesChartRef.value)
    const option = {
      title: {
        text: '设施问题统计',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: [],
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: '问题数量',
          type: 'bar',
          barWidth: '60%',
          data: [],
        },
      ],
    }
    issuesChart.setOption(option)
  }

  // 初始化时间分布图表
  if (timeDistributionChartRef.value) {
    timeDistributionChart = echarts.init(timeDistributionChartRef.value)
    const option = {
      title: {
        text: '设施添加时间分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: [],
          type: 'line',
          smooth: true,
          areaStyle: {},
        },
      ],
    }
    timeDistributionChart.setOption(option)
  }

  // 初始化地理分布热力图
  initMap()
}

// 初始化问题热力图
if (questionHeatmapChartRef.value) {
  questionHeatmapChart = echarts.init(questionHeatmapChartRef.value)
  const option = {
    title: {
      text: '问题热力图分析',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params: any) {
        return `权重值: ${params.value[2].toFixed(2)}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      name: 'X坐标',
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: {
      type: 'category',
      data: [],
      name: 'Y坐标',
      nameLocation: 'middle',
      nameGap: 30
    },
    visualMap: {
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%',
      inRange: {
        color: ['blue', 'green', 'yellow', 'red']
      }
    },
    series: [
      {
        name: '问题热力图',
        type: 'heatmap',
        data: [],
        pointSize: 8,
        blurSize: 10,
        coordinateSystem: 'cartesian2d',
        label: {
          show: false
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  questionHeatmapChart.setOption(option)
}

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'mapDiv',
      map: map,
      center: [116.3, 39.9], // 北京的经纬度
      zoom: 10,
    })

    // 创建学校设施要素图层
    facilityLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/7XPW9RycLUzz2YAj/arcgis/rest/services/SchoolFacilityManagement/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
    })

    // 添加图层到地图
    map.add(facilityLayer)
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 加载统计数据
const loadStatisticsData = async () => {
  if (!facilityLayer) return

  statisticsData.loading = true
  const loadingInstance = ElLoading.service({
    text: '正在加载统计数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    // 查询所有设施
    const query = new Query({
      where: '1=1', // 查询所有记录
      outFields: ['*'],
      returnGeometry: true,
    })

    const result = await facilityLayer.queryFeatures(query)
    const features = result.features

    // 更新总设施数
    statisticsData.totalFacilities = features.length

    // 按设施类型统计
    const typeCount: Record<string, number> = {}
    features.forEach((feature) => {
      const facilityType = feature.attributes.FacilityType || '未分类'
      typeCount[facilityType] = (typeCount[facilityType] || 0) + 1
    })

    // 转换为图表数据格式
    statisticsData.facilityTypeData = Object.entries(typeCount).map(([name, value]) => ({
      name,
      value,
    }))

    // 统计问题数量
    let totalIssues = 0
    const issuesByType: Record<string, number> = {}
    const allQuestions: Question[] = []

    features.forEach((feature) => {
      try {
        const issuesStr = feature.attributes.Issues || '[]'
        const issues = JSON.parse(issuesStr)
        const facilityType = feature.attributes.FacilityType || '未分类'

        // 累计问题数量
        issuesByType[facilityType] = (issuesByType[facilityType] || 0) + issues.length
        totalIssues += issues.length

        // 收集所有问题并添加位置信息
        if (issues.length > 0) {
          const geometry = feature.geometry as any
          issues.forEach((issue: any) => {
            allQuestions.push({
              ...issue,
              location: {
                x: geometry.x,
                y: geometry.y
              }
            })
          })
        }
      } catch (e) {
        console.error('解析问题数据失败:', e)
      }
    })

    statisticsData.totalIssues = totalIssues
    statisticsData.issuesData = Object.entries(issuesByType).map(([name, value]) => ({
      name,
      value,
    }))
    statisticsData.allQuestions = allQuestions

    // 生成问题热力图数据
    if (allQuestions.length > 0) {
      const heatmapData = generateHeatmapData(allQuestions)

      // 处理热力图数据，将坐标转换为离散的类别值
      const xCoords = Array.from(new Set(heatmapData.map(point => Math.round(point.x * 100) / 100)))
        .sort((a, b) => a - b)
      const yCoords = Array.from(new Set(heatmapData.map(point => Math.round(point.y * 100) / 100)))
        .sort((a, b) => a - b)

      // 将连续坐标转换为离散的类别索引
      const heatmapProcessedData = heatmapData.map(point => {
        const xIndex = xCoords.indexOf(Math.round(point.x * 100) / 100)
        const yIndex = yCoords.indexOf(Math.round(point.y * 100) / 100)
        return [xIndex, yIndex, point.value]
      })

      statisticsData.questionHeatmapData = heatmapProcessedData

      // 更新热力图的坐标轴数据
      if (questionHeatmapChart) {
        questionHeatmapChart.setOption({
          xAxis: {
            data: xCoords.map(x => x.toString())
          },
          yAxis: {
            data: yCoords.map(y => y.toString())
          }
        })
      }
    }

    // 按时间统计设施添加情况
    const dateCount: Record<string, number> = {}
    features.forEach((feature) => {
      // 使用CreationDate字段，如果没有则使用当前日期
      let dateStr = '未知日期'
      if (feature.attributes.CreationDate) {
        const date = new Date(feature.attributes.CreationDate)
        dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
      }
      dateCount[dateStr] = (dateCount[dateStr] || 0) + 1
    })

    // 按日期排序
    statisticsData.timeDistributionData = Object.entries(dateCount)
      .map(([date, count]) => ({ date, count }))
      .sort((a, b) => a.date.localeCompare(b.date))

    // 地理分布数据
    statisticsData.geographicData = features.map((feature) => {
      const geometry = feature.geometry as any
      return [geometry.x, geometry.y, 1] // 坐标和权重
    })

    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    statisticsData.loading = false
    loadingInstance.close()
  }
}

// 更新图表
const updateCharts = () => {
  // 更新设施类型分布图表
  if (facilityTypeChart) {
    facilityTypeChart.setOption({
      legend: {
        data: statisticsData.facilityTypeData.map((item) => item.name),
      },
      series: [
        {
          data: statisticsData.facilityTypeData,
        },
      ],
    })
  }

  // 更新设施问题统计图表
  if (issuesChart) {
    issuesChart.setOption({
      xAxis: [
        {
          data: statisticsData.issuesData.map((item) => item.name),
        },
      ],
      series: [
        {
          data: statisticsData.issuesData.map((item) => item.value),
        },
      ],
    })
  }

  // 更新时间分布图表
  if (timeDistributionChart) {
    timeDistributionChart.setOption({
      xAxis: {
        data: statisticsData.timeDistributionData.map((item) => item.date),
      },
      series: [
        {
          data: statisticsData.timeDistributionData.map((item) => item.count),
        },
      ],
    })
  }

  // 更新地理分布热力图
  if (geographicDistributionChart && statisticsData.geographicData.length > 0) {
    geographicDistributionChart.setOption({
      visualMap: {
        min: 0,
        max: 10,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: '15%',
      },
      series: [
        {
          name: '设施分布',
          type: 'heatmap',
          coordinateSystem: 'geo',
          data: statisticsData.geographicData,
          pointSize: 5,
          blurSize: 6,
        },
      ],
    })
  }

  // 更新问题热力图
  if (questionHeatmapChart && statisticsData.questionHeatmapData.length > 0) {
    // 计算最大值用于可视化映射
    const maxValue = Math.max(...statisticsData.questionHeatmapData.map(item => item[2]))

    questionHeatmapChart.setOption({
      visualMap: {
        min: 0,
        max: maxValue,
        calculable: true,
      },
      series: [
        {
          data: statisticsData.questionHeatmapData,
          coordinateSystem: 'cartesian2d',
          label: {
            show: false
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }
}

// 刷新数据
const refreshData = () => {
  loadStatisticsData()
}

// 窗口大小变化时重新调整图表大小
window.addEventListener('resize', () => {
  facilityTypeChart?.resize()
  issuesChart?.resize()
  timeDistributionChart?.resize()
  geographicDistributionChart?.resize()
  questionHeatmapChart?.resize()
})
</script>

<template>
  <div class="statistics-container">
    <div class="statistics-header">
      <h2 class="statistics-title">校园设施统计分析</h2>
      <el-button type="primary" @click="refreshData" :loading="statisticsData.loading">
        <el-icon><Refresh /></el-icon> 刷新数据
      </el-button>
    </div>

    <div class="statistics-summary">
      <el-card class="summary-card">
        <div class="summary-item">
          <div class="summary-icon facility-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 7V3H2V21H22V7H12ZM6 19H4V17H6V19ZM6 15H4V13H6V15ZM6 11H4V9H6V11ZM6 7H4V5H6V7ZM10 19H8V17H10V19ZM10 15H8V13H10V15ZM10 11H8V9H10V11ZM10 7H8V5H10V7ZM20 19H12V17H14V15H12V13H14V11H12V9H20V19ZM18 11H16V13H18V11ZM18 15H16V17H18V15Z" fill="#1976d2"/>
            </svg>
          </div>
          <div class="summary-content">
            <div class="summary-value">{{ statisticsData.totalFacilities }}</div>
            <div class="summary-label">设施总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="summary-card">
        <div class="summary-item">
          <div class="summary-icon issue-icon">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM13 17H11V15H13V17ZM13 13H11V7H13V13Z" fill="#f44336"/>
            </svg>
          </div>
          <div class="summary-content">
            <div class="summary-value">{{ statisticsData.totalIssues }}</div>
            <div class="summary-label">问题总数</div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="statistics-charts">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <div ref="facilityTypeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <div ref="issuesChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="12">
          <el-card class="chart-card">
            <div ref="timeDistributionChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <div id="mapDiv" class="map-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>问题热力图分析</span>
                <el-tooltip content="基于关键词分析、时间衰减和位置聚集度的智能问题分析系统生成的热力图">
                  <el-icon><info-filled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div ref="questionHeatmapChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}
.statistics-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.statistics-title {
  margin: 0;
  color: #1976d2;
  font-size: 24px;
}

.statistics-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.summary-card {
  flex: 1;
  max-width: 300px;
}

.summary-item {
  display: flex;
  align-items: center;
  padding: 10px;
}

.summary-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
}

.facility-icon {
  background-color: rgba(25, 118, 210, 0.1);
}

.issue-icon {
  background-color: rgba(244, 67, 54, 0.1);
}

.summary-content {
  display: flex;
  flex-direction: column;
}

.summary-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.chart-card {
  margin-bottom: 20px;
  height: 350px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.map-container {
  height: 300px;
  width: 100%;
}
</style>
